# -*- coding: utf-8 -*-
import uuid
from random import random

import os
from flask import Blueprint, render_template, request, redirect
from sqlalchemy import or_

from common.libs import Helper
from common.libs.Helper import ops_render, iPagination
from common.libs.Restful import Restful
from common.libs.UrlManager import UrlManager
from common.libs.user.UserService import UserService

from common.models.user import User

from application import app, db

route_account = Blueprint('account_page', __name__)


@route_account.route("/index")
def index():
    resp_data = {}
    req = request.values
    query = User.query
    # 分页
    page = int(req['p']) if ('p' in req and req['p']) else 1
    offset = (page - 1)*app.config['PAGE_SIZE']
    limit = app.config['PAGE_SIZE']*page
    userlist = query.filter_by(status=1).order_by(User.uid.desc()).all()[offset:limit]
    page_params = {
        'total': len(userlist),
        'page_size': app.config['PAGE_SIZE'],
        'page': page,
        'display': app.config['PAGE_DISPLAY'],
        'url': request.full_path.replace('?p={}'.format(page), '').replace('?', '')
    }
    search_data = {
        'kw': '',
        'st': ''
    }
    pages = iPagination(page_params)
    return ops_render("account/index.html", context={'userlist': userlist, 'pages': pages, 'search_data': search_data})


@route_account.route("/info")
def info():
    uid = request.args.get('id')
    if not uid:
        return redirect(UrlManager.buildUrl('/account/index'))
    user = User.query.filter_by(uid=uid).first()
    if not user:
        return redirect(UrlManager.buildUrl('/account/index'))

    return ops_render("account/info.html", context={'user': user})


@route_account.route("/set", methods=['GET', 'POST'])
def set():
    if request.method == 'GET':
        uid = request.args.get('id')
        method = request.args.get('m')
        if method == 'update':
            if not uid:
                return redirect(UrlManager.buildUrl('/account/index'))
            user = User.query.filter_by(uid=uid).first()
            if not user:
                return redirect(UrlManager.buildUrl('/account/index'))
            return ops_render("account/set.html", context={'user': user})
        else:
            return ops_render("account/set.html", context={'user': {
                'nickname': '',
                'mobile': '',
                'email': '',
                'login_name': '',
                'login_pwd': ''
            }})

    resp = request.values
    nickname = resp.get('nickname')
    mobile = resp.get('mobile')
    email = resp.get('email')
    login_name = resp.get('login_name')
    login_pwd = resp.get('login_pwd')
    method = resp.get('method')
    uid = resp.get('id')
    if method == 'add':
        aluser = User.query.filter_by(login_name=login_name).first()
        if aluser:
            return Restful.format_error(msg='该用户名已存在', code=123)
        user = User()
        user.nickname = nickname
        user.mobile = mobile
        user.email = email
        user.login_name = login_name
        user.login_salt = UserService.geneSalt()
        user.login_pwd = UserService.genePwd(login_pwd, user.login_salt)
        db.session.add(user)
        db.session.commit()
        return Restful.success(msg='用户添加成功')
    elif method == 'update':
        if not uid:
            return Restful.notfound_error(msg='没有找到此用户')
        aluser = User.query.get(uid)
        if not aluser:
            return Restful.notfound_error(msg='没有找到此用户')

        aluser.nickname = nickname
        aluser.mobile = mobile
        aluser.email = email
        aluser.login_name = login_name
        if login_pwd != '******':
            if UserService.genePwd(login_pwd, aluser.login_salt) != aluser.login_pwd:
                aluser.login_pwd = UserService.genePwd(login_pwd, aluser.login_salt)
        db.session.commit()
        return Restful.success('用户信息修改成功')
    else:
        return Restful.param_error('参数错误')


@route_account.route('/search/', methods=['POST', 'GET'])
def search():
    req = request.values
    kw = req.get('kw')
    st = int(req.get('st', 0))
    page = int(req['p']) if ('p' in req and req['p']) else 1
    offset = (page - 1) * app.config['PAGE_SIZE']
    limit = app.config['PAGE_SIZE'] * page
    query = User.query
    query = query.filter(or_(User.nickname.like('%'+ kw +'%'), User.mobile.like('%'+ kw +'%')))
    if st > -1:
        query = query.filter(User.status == int(st))
    userlist = query.all()[offset:limit]
    page_params = {
        'total': len(userlist),
        'page_size': app.config['PAGE_SIZE'],
        'page': page,
        'display': app.config['PAGE_DISPLAY'],
        'url': request.full_path.replace('?p={}'.format(page), '')
    }
    pages = iPagination(page_params)
    search_data = {
        'kw': kw,
        'st': st
    }
    return ops_render('account/index.html', context={'userlist': userlist, 'pages': pages, 'search_data': search_data})


@route_account.route('/delete/', methods=['POST'])
def delete():
    uid = request.form.get('uid')
    if not uid:
        return Restful.param_error(msg='缺少参数！')
    user = User.query.filter_by(uid=uid).first()
    if not user:
        return Restful.notfound_error(msg='没有找到此用户！')
    user.status = 0
    user.updated_time = Helper.geneDatetime()
    db.session.commit()
    return Restful.success()


@route_account.route('/reload/', methods=['POST'])
def reload():
    uid = request.form.get('uid')
    if not uid:
        return Restful.param_error(msg='缺少参数！')
    user = User.query.filter_by(uid=uid).first()
    if not user:
        return Restful.notfound_error(msg='没有找到此用户！')
    user.status = 1
    user.updated_time = Helper.geneDatetime()
    db.session.commit()
    return Restful.success()